package com.bootdo.merchant.serivce.impl;

import static com.bootdo.common.utils.ShiroUtils.getUserId;

import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Isolation;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

import com.alibaba.fastjson.JSONObject;
import com.bootdo.common.config.Constant;
import com.bootdo.common.utils.DateUtils;
import com.bootdo.common.utils.MD5Utils;
import com.bootdo.common.utils.StringUtils;
import com.bootdo.merchant.dao.AgentDao;
import com.bootdo.merchant.dao.MerchantDao;
import com.bootdo.merchant.domain.AgentDO;
import com.bootdo.merchant.domain.MerchantDO;
import com.bootdo.merchant.serivce.AgentService;
import com.bootdo.mq.RabbitUtil;
import com.bootdo.quota.dao.QuotaDao;
import com.bootdo.quota.dao.QuotaHistoryDao;
import com.bootdo.quota.domain.QuotaDO;
import com.bootdo.quota.domain.QuotaHistoryDO;
import com.bootdo.system.dao.UserDao;
import com.bootdo.system.dao.UserRoleDao;
import com.bootdo.system.domain.UserDO;
import com.bootdo.system.domain.UserRoleDO;

/**
 * @Desc 商户代理管理
 * @date 2019/11/12
 *
 */
@Service
public class AgentServiceImpl implements AgentService {

    @Autowired
    private UserDao userMapper;
    @Autowired
    private AgentDao agentMapper;
    @Autowired
    private UserRoleDao userRoleMapper;
    @Autowired
    private QuotaDao quotaMapper;
    @Autowired
    private MerchantDao merchantMapper;
    @Autowired
    private QuotaHistoryDao quotaHistoryMapper;
    @Autowired
    private RabbitUtil rabbitUtil;

    /**
     * 获取指定商户信息
     * @param id
     * @return
     */
    @Override
    public AgentDO get(Long id) {
        return agentMapper.get(id);
    }


    /**
     * 获取商户代理列表
     * @param map
     * @return
     */
    @Override
    public List<AgentDO> list(Map<String, Object> map){
        //获取用户权限
        int checkUserIsManager = userRoleMapper.checkUserIsManager(getUserId());
        if (checkUserIsManager != 1){
            map.put("userIdCreate", getUserId());
        }
        return agentMapper.list(map);
    }

    /**
     * 获取商户代理列表总条数
     * @param map
     * @return
     */
    @Override
    public int count(Map<String, Object> map){
        return agentMapper.count(map);
    }

    /**
     * 添加商户代理
     * @param agentDO
     * @return
     */
    @Override
    @Transactional(propagation = Propagation.REQUIRED,isolation = Isolation.DEFAULT,timeout=36000,rollbackFor=Exception.class)
    public int save(AgentDO agentDO){
        agentDO.setUserName(agentDO.getUserName().trim());
        agentDO.setName(agentDO.getName().trim());
        //添加用户表
        UserDO userDO = new UserDO();
        userDO.setUsername(agentDO.getUserName());
        userDO.setPassword(agentDO.getPassword());
        userDO.setStatus(1);
        userDO.setMobile(agentDO.getMobile());
        userMapper.save(userDO);

        Long userId = userDO.getUserId();
        userRoleMapper.removeByUserId(userId);
        UserRoleDO ur = new UserRoleDO();
        ur.setUserId(userId);
        ur.setRoleId(60L);
        userRoleMapper.save(ur);

        agentDO.setUserId(userId);
        agentDO.setUserIdCreate(getUserId());
        agentDO.setGmtCreate(new Date());
        int count = agentMapper.save(agentDO);

        //设置余额
        QuotaDO quota = new QuotaDO();
        quota.setUserId(userId);
        quota.setChangeReason("初始额度");
        quota.setStatus(1);
        quota.setActualQuota(0.00);
        quota.setQuota(0.00);
        quota.setChangeType(0);
        quota.setGmtDate(new Date());
        quotaMapper.save(quota);

        //插入历史表
        QuotaHistoryDO quotaHistory = new QuotaHistoryDO();
        quotaHistory.setUserId(userId);
        quotaHistory.setQuota(0.00);
        quotaHistory.setActualQuota(0.00);
        quotaHistory.setChangeReason("初始额度");
        quotaHistory.setStatus(1);
        quotaHistory.setChangeType(0);
        quotaHistory.setGmtDate(new Date());
        quotaHistory.setVersion(1);
        quotaHistoryMapper.save(quotaHistory);

        return count;
    }

    /**
     * 更新商户代理
     * @param agentDO
     * @return
     */
    @Override
    @Transactional(propagation = Propagation.REQUIRED,isolation = Isolation.DEFAULT,timeout=36000,rollbackFor=Exception.class)
    public int update(AgentDO agentDO){
        if (StringUtils.isNotBlank(agentDO.getUserName())){
            agentDO.setUserName(agentDO.getUserName().trim());
        }
        if (StringUtils.isNotBlank(agentDO.getName())){
            agentDO.setName(agentDO.getName().trim());
        }

        String password = agentDO.getPassword();
        AgentDO agent = agentMapper.get(agentDO.getUserId());
        if (StringUtils.isBlank(password) || password.equals(agent.getPassword())){
            agentDO.setPassword(null);
        } else {
            agentDO.setPassword(MD5Utils.encrypt(agent.getUserName(), password));
            UserDO user = new UserDO();
            user.setUserId(agentDO.getUserId());
            user.setPassword(agentDO.getPassword());
            userMapper.update(user);
        }
        int count = agentMapper.update(agentDO);

        //修改用户状态
        if (agentDO.getStatus() != null) {
            UserDO user = new UserDO();
            user.setUserId(agentDO.getUserId());
            user.setStatus(agentDO.getStatus());
            userMapper.update(user);
        }

        //修改余额
        QuotaDO quota = quotaMapper.get(agentDO.getUserId());
        if (agentDO.getQuota() != null && agentDO.getQuota().doubleValue() != quota.getActualQuota().doubleValue()){
            JSONObject object = new JSONObject();
            object.put("date", DateUtils.format(new Date(),DateUtils.DATE_TIME_PATTERN));
            object.put("userId", agentDO.getUserId());
            object.put("money",agentDO.getQuota());
            object.put("orderId", "");
            if (agentDO.getQuota().doubleValue() > quota.getActualQuota().doubleValue()){
                object.put("reason", "平台调整增加");
                object.put("type", 1);
            } else {
                object.put("reason", "平台调整减少");
                object.put("type", 2);
            }
            rabbitUtil.sendToQueue(Constant.UPDATE_QUOTA, object.toJSONString());
        }
        return count;
    }


    /**
     * 商户代理状态修改
     * @param userId
     * @param status
     * @return
     */
    @Override
    @Transactional(propagation = Propagation.REQUIRED,isolation = Isolation.DEFAULT,timeout=36000,rollbackFor=Exception.class)
    public int editStatus(Long userId, Integer status){
        AgentDO agentDO = new AgentDO();
        agentDO.setUserId(userId);
        agentDO.setGmtModified(new Date());
        agentDO.setStatus(status);
        int count = agentMapper.update(agentDO);

        UserDO user = new UserDO();
        user.setUserId(agentDO.getUserId());
        user.setStatus(agentDO.getStatus());
        userMapper.update(user);

       if (agentDO.getStatus() == 0){
           //商户代理禁用后需要将所有的下属商户禁用
           MerchantDO merchant = new MerchantDO();
           merchant.setUserIdCreate(agentDO.getUserId());
           merchant.setStatus(agentDO.getStatus());
           merchantMapper.editStatusByCreate(merchant);

           Map<String,Object> map = new HashMap<>();
           map.put("userIdCreate", agentDO.getUserId());
           List<MerchantDO> lists = merchantMapper.list(map);
           List<Long> list = new ArrayList<>();
           for (MerchantDO merchants : lists){
               list.add(merchants.getUserId());
           }
           userMapper.batchStatus(list);
       }
        return count;
    }

    /**
     * 重置商户代理令牌
     * @param id
     * @return
     */
    @Override
    @Transactional(propagation = Propagation.REQUIRED,isolation = Isolation.DEFAULT,timeout=36000,rollbackFor=Exception.class)
    public int resetToken(Long id){
        return userMapper.removeSecretById(id);
    }

}
